#ifndef POLYPHONYCHANNEL_H
#define POLYPHONYCHANNEL_H

#include "samplerglobals.h"

using namespace sampler;
class PolyphonyChannel {
public:
    PolyphonyChannel(size_t bufsize) :
        buffer_(new gl::PcmSampleType[bufsize]), file_(NULL),
        buffer_counter_(0), note_(0,0), buf_size_(bufsize)
    {
    }

    ~PolyphonyChannel(){ delete[] buffer_; }

    inline bool read(size_t amnt){ // true if end of file
        size_t done = 0;
        bool is_eof = false;
        gl::PcmSampleType * begin = buffer_ + buffer_counter_;
        if (file_ != NULL)
            done = sf_readf_float( file_, begin, amnt);
        if (is_eof = (done < amnt))
            memset ( begin + done, 0,
                     sizeof(gl::PcmSampleType) * (amnt - done));
        buffer_counter_ += amnt;
        return is_eof;
    };

    inline void setNote(SNDFILE * new_file,
                        const Note & new_note, size_t position) {
        Q_ASSERT (new_file != NULL);
        Q_ASSERT (position < buf_size_);
        gl::log("PCH : position is %1", position);        
        read (position - buffer_counter_);
        file_ = new_file;
        note_ = new_note;
        sf_seek(file_, 0, SEEK_SET);
    }

    inline const gl::PcmSampleType * process(bool & isActive) {
        size_t rest_amnt = buf_size_ - buffer_counter_;
        isActive = ! read(rest_amnt);
        buffer_counter_ = 0;
        return buffer_;
    }

    inline char note(){return note_.note;}
    inline char velocity(){return note_.vel;}

private:
    gl::PcmSampleType * buffer_;
    SNDFILE * file_;
    size_t buffer_counter_;
    sampler::Note note_;
    size_t buf_size_;
};
#endif // POLYPHONYCHANNEL_H
